import { Component, ChangeDetectorRef, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material';
import { MediaMatcher } from '@angular/cdk/layout';
import { RestService } from '../services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { UserInfoDialogComponent } from './user-info-dialog/user-info-dialog.component';

import * as _ from 'lodash';

@Component({
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit, OnDestroy {
  mobileQuery: MediaQueryList;
  currentApp = '';
  user: any;
  institution: any;

  private _mobileQueryListener: () => void;

  constructor(public dialog: MatDialog,
              private router: Router,
              private restService: RestService,
              private changeDetectorRef: ChangeDetectorRef,
              private media: MediaMatcher) {
    this.mobileQuery = media.matchMedia('(max-width: 600px)');
    this._mobileQueryListener = () => changeDetectorRef.detectChanges();
    this.mobileQuery.addListener(this._mobileQueryListener);

    this.currentApp = 'mcenter';
    this.restService.setCurrentApp(this.currentApp);
    const urls = this.router.url.split('/');
    if (urls.length === 3) {
      this.currentApp = urls[2];
      this.restService.setCurrentApp(this.currentApp);
    }

    this.user = this.restService.getUser();
    if (!this.user || !this.user.name || !this.user.role) {
      console.error('Invalid user or user role: empty!');
      this.logout(null);
    }

    this.institution = this.restService.getInstitution();
    console.log('Institution id is now set to: ' + this.institution.id);

    this.restService.eventEmit.subscribe(value => {
      if (value === 'mcenter') {
        this.restService.setCurrentApp('mcenter');
        this.currentApp = 'mcenter';
      }
    });
  }

  isAdminUser() {
    return this.user.role === 'super' || this.user.role === 'admin';
  }

  isUserQalified(app) {
    switch (app) {
    case 'mcenter':
    case 'map':
    case 'monitor':
    case 'person':
    case 'alarm':
    case 'nurse':
      return this.user.role === 'director' ||
             this.user.role === 'header' ||
             this.user.role === 'nurse' ||
             this.user.role === 'doctor';
    case 'bed':
    case 'device':
      return this.user.role === 'director' ||
             this.user.role === 'header' ||
             this.user.role === 'doctor';
    case 'user':
    case 'department':
      return this.user.role === 'admin' ||
             this.user.role === 'director';
    case 'menu':
      return this.user.role === 'super' ||
             this.user.role === 'admin' ||
             this.user.role === 'director';
    case 'institution':
      return this.user.role === 'super';
    }

    return true;
  }

  openUserInfo() {
    this.dialog.open(UserInfoDialogComponent, {
      disableClose: false,
      autoFocus: false,
      width: '400px',
      data: {}
    });
  }

  navigateTo(item) {
    this.currentApp = item;
    this.restService.setCurrentApp(this.currentApp);
    this.router.navigateByUrl('/home/' + item);
  }

  logout(event) {
    this.restService.reload2Login();
  }

  ngOnInit() {
    // try to get correct institution id
    if (this.institution.id === -1) {
      if (this.user.role === 'super') {
        this.navigateTo('institution');
      }
    } else if (this.institution.id === 0) {
      this.restService.getWithParams('data/institution/search/name', {name: this.institution.instName}).subscribe(data => {
        const insts = data['_embedded']['institutions'];
        if (insts.length > 0) {
          const index = _.findIndex(insts, {instName: this.institution.instName});
          this.institution = insts[index];
          this.restService.saveInstitution(this.institution);

          if (this.user.role === 'super') {
            this.navigateTo('institution');
          } else if (this.user.role === 'admin') {
            this.navigateTo('department');
          } else {
            this.navigateTo('mcenter');
          }
        } else {
          console.error('Failed to get instituion (empty): ' + this.institution.instName);
          if (this.user.role === 'super') {
            this.navigateTo('institution');
          }
        }
      }, () => {
        console.error('Failed to get instituion ' + this.institution.instName);
        if (this.user.role === 'super') {
          this.navigateTo('institution');
        }
      });
    } else {
      if (this.user.role === 'super') {
        this.navigateTo('institution');
      } else if (this.user.role === 'admin') {
        this.navigateTo('department');
      } else {
        this.navigateTo('mcenter');
      }
    }
  }

  ngOnDestroy() {
    this.mobileQuery.removeListener(this._mobileQueryListener);
  }
}
